package org.person.gift.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.person.gift.clients.GiftClient;
import org.person.gift.domain.ShopCar;
import org.person.gift.dto.AddShopCarDTO;
import org.person.gift.dto.DeleteDTO;
import org.person.gift.dto.UpdateNumDTO;
import org.person.gift.dto.UpdateSelectDTO;
import org.person.gift.exception.BusinessException;
import org.person.gift.exception.ResponseCode;
import org.person.gift.exception.SystemAssert;
import org.person.gift.mapper.ShopCarMapper;
import org.person.gift.service.IShopCarService;
import org.person.gift.util.AjaxResult;
import org.person.gift.util.encrypt.TenantIdName;
import org.springframework.beans.factory.annotation.Autowired;
import org.person.gift.domain.GoodsSku;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author stark
 * @since 2024-02-21
 */
//@Service
public class ShopCarServiceImpl_mysql extends ServiceImpl<ShopCarMapper, ShopCar> implements IShopCarService {

    @Autowired
    private GiftClient giftClient;

    @Override
    @Transactional
    public void addShopCar(AddShopCarDTO dto) {
        //参数校验
        //非空校验 skuId
        SystemAssert.isNotNull(dto.getSkuId(), ResponseCode.RESPONSE_CODE_500);
        //根据userId&skuId查询购物车数据
        Wrapper<ShopCar> wrapper = new EntityWrapper<ShopCar>()
                .eq("sku_id",dto.getSkuId())
                .and()
                .eq("user_id",dto.getUserId());
        ShopCar shopCar = selectOne(wrapper);
        //如果存在就修改购物车的num
        if (Objects.nonNull(shopCar)){
            shopCar.setNum(shopCar.getNum()+dto.getNum());
            shopCar.setUpdateTime(new Date());
            updateById(shopCar);
        }else {
            //不存在则调用礼物服务查询商品skuId
            AjaxResult ajaxResult = giftClient.get(dto.getSkuId());
            boolean success = ajaxResult.isSuccess();
            if (!success){
                throw new BusinessException(ajaxResult.getMessage());
            }
            //封装shopCar对象
            String jsonStr = JSONObject.toJSONString(ajaxResult.getResultObj());
            GoodsSku goodsSku = JSONObject.parseObject(jsonStr,GoodsSku.class);
            ShopCar car = new ShopCar();
            car.setSpuId(goodsSku.getSpuId());
            car.setSpuName(goodsSku.getSpuName());
            car.setSkuId(goodsSku.getId());
            car.setSkuInfo(goodsSku.getSkuName());
            car.setAddPrice(goodsSku.getPrice());
            car.setPrice(goodsSku.getPrice());
            car.setUserId(dto.getUserId());
            car.setUsername(dto.getUsername());
            car.setTenantId(goodsSku.getTenantId());
            car.setTenantName(goodsSku.getTenantId()+"");
            car.setSelect(true);    // 第一次新增的时候,默认是选中
            car.setCreateTime(new Date());
            car.setNum(dto.getNum());
        }

    }

    @Override
    public void updateNum(UpdateNumDTO dto) {
        //根据购物车的ID查询数据
        ShopCar id = selectById(dto.getShopCarId());
        //如果不存在，返回错误信息
        SystemAssert.isNotNull(id,ResponseCode.RESPONSE_CODE_40009);
        //如果存在，修改数量
        id.setNum(dto.getNum());
        id.setUpdateTime(new Date());
        updateById(id);
    }

    @Override
    public void updateSelect(UpdateSelectDTO dto) {
        //根据购物车的ID查询数据
        ShopCar id = selectById(dto.getShopCarId());
        //如果不存在，返回错误信息
        SystemAssert.isNotNull(id,ResponseCode.RESPONSE_CODE_40009);
        //如果存在，修改状态
        id.setSelect(dto.getSelect());
        id.setUpdateTime(new Date());
        updateById(id);
    }

    @Override
    public Map<TenantIdName, List<ShopCar>> getShopCarList(Long userId) {
        // 1  根据userId查询出当前用户所有的购物车数据  list
        Wrapper<ShopCar> wrapper = new EntityWrapper<ShopCar>().eq("user_id", userId);
        List<ShopCar> shopCars = selectList(wrapper);

        Map<TenantIdName, List<ShopCar>> map = new HashMap<>();
        if(shopCars == null || shopCars.size() == 0){
            return map;
        }
        // 2 根据租户ID进行分组,同一个店铺下的商品要在同一个店铺下
        // 方案一: 循环list, 判断当前商品所在的店铺key有没有,有就放入对应的value中,如果没有就重新put
        /*for (ShopCar shopCar : shopCars) {
            TenantIdName tenantIdName = new TenantIdName(shopCar.getTenantId(), shopCar.getTenantName());
            if(map.containsKey(tenantIdName)){
                // 如果该租户已存在,就直接往value中Add
                List<ShopCar> carList = map.get(tenantIdName);
                carList.add(shopCar);
            }else{
                map.put(tenantIdName,Arrays.asList(shopCar));
            }
        }*/
        // 方案二  lamdba表达式
        // 将shopCars集合循环,并按照租户ID和名字做分组
        Map<TenantIdName, List<ShopCar>> listMap = shopCars.stream().collect(Collectors.groupingBy(x -> {
            return new TenantIdName(x.getTenantId(), x.getTenantName());
        }));
        return listMap;
    }

    @Override
    public void deleteByRedis(DeleteDTO dto) {

    }

    @Override
    public void dataSync() {

    }
}
